//
//  AIGirlUserInfoChooseViewController.swift
//  AIGirl
//
//  Created by Rae on 2023/12/27.
//

import UIKit

class AIGirlUserInfoChooseViewController: AIGirlBaseViewController {

    private lazy var backView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).end()
    private lazy var backButton = c_make_ex(UIButton.self)
        .image("AIGirl_Signin_back").end()
    private var sliderView = AIGirlMeansSliderView()
    private lazy var titleLabel = c_make_ex(UILabel.self)
        .color(.white).font(22.font_bold).alignment(.center)
        .text("Pick your girl").end()
    private var nameView = AIGirlNameView()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private lazy var nextButton = c_make_ex(AIGirlSubmitButton.self)
        .color(.white).font(21.font_bold).corner(20)
        .text("Next").end()
    
    private var imgStr: String = ""
    var dataList:[AIGirlItemModel] = []
    private var girlId = 0
    private var modelId = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadData()
        
        view.subviews{
            backView
            backButton
            sliderView
            titleLabel
            nameView
            collectionView
            nextButton
        }
        
        backView.fillContainer()
        backButton.leading(15).top(.statusHeight).size(30)
        sliderView.leading(37.5).trailing(37.5).height(4.5)
        sliderView.Top == backButton.Bottom + 12
        titleLabel.leading(15).trailing(15)
        titleLabel.Top == sliderView.Bottom + 55
        nameView.leading(0).trailing(0).bottom(0)
        nameView.Top == titleLabel.Bottom
        nextButton.leading(37.5).trailing(37.5).height(50).bottom(60)
        collectionView.leading(0).trailing(0).height(45)
        collectionView.Bottom == nextButton.Top - 35
        
        sliderView.value = 70
        nameView.isHidden = true
        nameView.title = "What name for your sweetheart?"
        nameView.placeholder = "Pick a name for her"
        nameView.nextClosure = { nameStr in
            
            self.request.start(.setGirlName(girlId: self.girlId, modelId: self.modelId, name: nameStr)) { result in
                if result.isSuccessful {
                    UserDefaultsManager.setInt(5, forKey: .currentPage)
                    UserDefaultsManager.setString(nameStr, forKey: .grilName)
                    self.navigationController?.pushViewController(AIGirlUserInfoTopicViewController(), animated: true)
                }
            }
        }
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 15
        layout.itemSize = CGSize(width: 40.0, height: 45.0)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 37.5, bottom: 0, right: 0)
        layout.scrollDirection = .horizontal
        collectionView.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(AIGirlUserInfoChooseItem.self, forCellWithReuseIdentifier: AIGirlUserInfoChooseItem.description())
            v.showsHorizontalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        nextButton.addTarget(self, action: #selector(clickNextButton), for: .touchUpInside)
        
        if UserDefaultsManager.getInt(forKey: .currentPage) == 4 {
            self.nameView.isHidden = false
            self.collectionView.isHidden = true
            self.nextButton.isHidden = true
        }
    }
    
    private func loadData(){
        
        self.request.start(.girlList(num: 1, size: 100, startIndex: 0, type: 0), type: AIGirlListModel.self) { result in
            
            if result.isSuccessful, let model = result.model {
                var dataSource = [AIGirlItemModel]()
                dataSource = model.rows
                var index = 0
                for var itemM in dataSource {
                    index += 1
                    if index == 1 {
                        self.imgStr = itemM.image
                        self.backView.loadImage(url: itemM.image)
                        self.girlId = itemM.girlId
                        self.modelId = itemM.modelId
                        itemM.isSel = true
                    }else{
                        itemM.isSel = false
                    }
                    self.dataList.append(itemM)
                }
                self.collectionView.reloadData()
            }
        }

    }
    
    @objc private func clickNextButton(){
        
        if girlId != 0 && modelId != 0 {
            
            request.start(.saveMyGirl(girlId: girlId, modelId: modelId)) { result in
                if result.isSuccessful {
                    UserDefaultsManager.setInt(4, forKey: .currentPage)
                    UserDefaultsManager.setInt(self.girlId, forKey: .girlId)
                    UserDefaultsManager.setInt(self.modelId, forKey: .modelId)
                    UserDefaultsManager.setString(self.imgStr, forKey: .girlAvatar)
                    self.nameView.isHidden = false
                    self.collectionView.isHidden = true
                    self.nextButton.isHidden = true
                }
            }
        }
    }
}


extension AIGirlUserInfoChooseViewController: UICollectionViewDelegate,UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: AIGirlUserInfoChooseItem.description(), for: indexPath) as? AIGirlUserInfoChooseItem else { return UICollectionViewCell() }
        item.model = dataList[indexPath.row]
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        var models = [AIGirlItemModel]()
        dataList.forEach { model in
            var itemModel = model
            itemModel.isSel = false
            models.append(itemModel)
        }
        models[indexPath.row].isSel = true
        self.imgStr = models[indexPath.row].image
        self.backView.loadImage(url: models[indexPath.row].image)
        self.girlId = models[indexPath.row].girlId
        self.modelId = models[indexPath.row].modelId
        dataList = models
        collectionView.reloadData()
    }
}

class AIGirlUserInfoChooseItem: UICollectionViewCell {
    
    private let iconImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).corner(12).end()
    private let selImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).image("AIGirl_Signin_girlSel").end()
    private let preImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).image("AIGirl_Signin_pre").end()
    
    var model: AIGirlItemModel? {
        didSet{
            guard let md = model else {
                return
            }
            iconImageView.loadImage(url: md.image)
            selImageView.isHidden = !md.isSel
            preImageView.isHidden = !(md.isVip == 1)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.subviews {
            iconImageView.subviews{
                selImageView
            }
            preImageView
        }

        iconImageView.fillContainer()
        selImageView.fillContainer()
        preImageView.trailing(0).bottom(0).size(14)
        
        selImageView.isHidden = true
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
